package com.ycz.sas.jgen.ui;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;

import com.ycz.sas.jgen.handler.ConfigDataHandler;
import com.ycz.sas.jgen.handler.FileOprate;
import com.ycz.sas.jgen.main.ContextUtil;

public class BatchJarUI extends JDialog implements Runnable{

	private ConfigDataHandler handler;
	private List<String> startList;
	private Map<String,String> endList;
	private String defaultPath;
	private boolean isStart;

	private JTextArea taStartList;
	private JTextArea taEndList;

	private JButton btnAddConfigFile;
	private JButton btnAddAllConfig;
	private JButton btnStart;

	private JProgressBar pbjobs;

	public BatchJarUI(JFrame owner, boolean modal){
		super(owner, modal);
		reset();
		isStart = false;

		initLayout();

		addWindowListener(new WindowListener() {
			@Override
			public void windowOpened(WindowEvent e) {}
			@Override
			public void windowIconified(WindowEvent e) {}
			@Override
			public void windowDeiconified(WindowEvent e) {}
			@Override
			public void windowDeactivated(WindowEvent e) {}
			@Override
			public void windowClosing(WindowEvent e) {
				handler.releaseAllCfgFile();
			}
			@Override
			public void windowClosed(WindowEvent e) {
			}
			@Override
			public void windowActivated(WindowEvent e) {}
		});
	}

	public BatchJarUI(JFrame owner, boolean modal, String defaultPath){
		this(owner, modal);
		this.defaultPath = defaultPath;
	}

	private void reset(){
		handler = new ConfigDataHandler();
		startList = new ArrayList<String>();
		endList = new HashMap<String,String>();
	}

	@Override
	public String getTitle() {
		return "批量分包";
	}

	protected void initLayout(){
		setSize(690, 390);
		setResizable(false);
		Container contentPane = getContentPane();

		JPanel pnlList = new JPanel();
		pnlList.setLayout(new FlowLayout(0));
		contentPane.add(pnlList,"Center");


		taStartList = new JTextArea(17,10);
		taStartList.setEditable(false);
		taEndList = new JTextArea(17,50);
		taEndList.setEditable(false);
		JScrollPane scrollstart = new JScrollPane();
		scrollstart.setViewportView(taStartList);
		JScrollPane scrollend = new JScrollPane();
		scrollend.setViewportView(taEndList);

		pnlList.add(scrollstart);
		pnlList.add(scrollend);

		JPanel pnlControl = new JPanel();
		pnlControl.setLayout(new FlowLayout(0));
		contentPane.add(pnlControl,"South");

		pbjobs = new JProgressBar();
		pbjobs.setStringPainted(true);
		pbjobs.setString("0%");
		pbjobs.setForeground(Color.BLUE);
		btnAddConfigFile = new JButton("添加模块");
		btnAddAllConfig = new JButton("添加所有模块");
		btnStart = new JButton("执行任务");
		pnlControl.add(btnAddConfigFile);
		pnlControl.add(btnAddAllConfig);
		pnlControl.add(btnStart);
		pnlControl.add(pbjobs);

		btnAddConfigFile.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileFilter(new FileFilter() {

					@Override
					public String getDescription() {
						String strFileDesc = "Config File(*.cfg)";
						return strFileDesc;
					}

					@Override
					public boolean accept(File file) {
						String strFileExt = ".cfg";
						if(file.isDirectory() || file.getName().endsWith(strFileExt))
							return true;
						else
							return false;
					}
				});
				chooser.setAcceptAllFileFilterUsed(false);
				chooser.setMultiSelectionEnabled(true);
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				chooser.setDialogTitle("请选择配置模块");
				chooser.setCurrentDirectory(new File(defaultPath));
				int ok = chooser.showDialog(BatchJarUI.this, "ADD");
				if (ok == JFileChooser.OPEN_DIALOG) {
					File[] cfgFiles = chooser.getSelectedFiles();
					for(File file : cfgFiles){
						if (file.exists()) {
							String fileName = file.getAbsolutePath();
							if(!startList.contains(fileName)){
								startList.add(fileName);
								handler.lockCfgFile(fileName);
							}
						}
					}
					taStartList.setText(getStartListString());
					taEndList.setText(getEndListString());
					pbjobs.setValue(0);
					pbjobs.setString("0%");
				}
			}
		});
		
		btnAddAllConfig.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				File f = new File(defaultPath);
				File[] cfgFiles = f.listFiles();
				for(File file : cfgFiles){
					if (file.exists()) {
						String fileName = file.getAbsolutePath();
						if(!startList.contains(fileName)){
							startList.add(fileName);
							handler.lockCfgFile(fileName);
						}
					}
				}
				taStartList.setText(getStartListString());
				taEndList.setText(getEndListString());
				pbjobs.setValue(0);
				pbjobs.setString("0%");
			}
			
		});

		btnStart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if(isStart){
					JOptionPane.showMessageDialog(BatchJarUI.this, "任务正在执行中...");
				}else{
					Thread thread = new Thread(BatchJarUI.this);
					thread.setName("Thread for Generate JarFiles");
					thread.start();
				}
			}
		});
	}

	private String getStartListString(){
		StringBuffer buffer = new StringBuffer();
		for (int i = 0, len = startList.size(); i < len; i++) {
			String fileName = new File(startList.get(i)).getName();
			buffer.append(fileName).append("\n");
		}
		return buffer.toString();
	}

	private String getEndListString(){
		StringBuffer buffer = new StringBuffer();
		for (Iterator iterator = endList.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
			buffer.append(entry.getKey()).append("\t\t");
			buffer.append(entry.getValue()).append("\n");
		}
		return buffer.toString();
	}

	final Runnable plan = new Runnable() {

		@Override
		public void run() {
			while(startList.size() != 0){
				taStartList.setText(getStartListString());
				taEndList.setText(getEndListString());

				int total = startList.size() + endList.size();
				int complete = endList.size();

				float progress = (float)complete/(float)total * 100;

				pbjobs.setValue((int)progress);
				pbjobs.setString((int)progress + "%");

				try {
					Thread.sleep(100l);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			taStartList.setText(getStartListString());
			taEndList.setText(getEndListString());

			int total = startList.size() + endList.size();
			int complete = endList.size();

			float progress = (float)complete/(float)total * 100;

			pbjobs.setValue((int)progress);
			pbjobs.setString((int)progress + "%");

			JOptionPane.showMessageDialog(BatchJarUI.this, "任务执行成功！");

			reset();
		}
	};

	protected void checkFileTree() throws Exception{
		if(startList.size() <= 0){
			JOptionPane.showMessageDialog(this, "Please Load Config File");
			throw new Exception();
		}
	}

	@Override
	public void run() {
        try {
        	checkFileTree();
        	isStart = true;
        	btnAddConfigFile.setEnabled(false);
        	btnAddAllConfig.setEnabled(false);

        	Thread t = new Thread(plan);
        	t.setName("Thread for Show Progress");
        	t.start();

        	//执行打jar包程序

        	while(!startList.isEmpty()){
        		String cfgFile = startList.get(0);
        		String cfgName = new File(cfgFile).getName();
        		handler.getCache().getPaths().clear();
        		handler.getCache().getDiffFiles().clear();
        		handler.getCache().setConfigPath(cfgFile);
        		handler.loadConfigData(cfgFile);
        		handler.analyse();
        		List<File> diffFiles = handler.getCache().getDiffFiles();
        		if(diffFiles.size() > 0){
        			String jarPath = handler.generateJar();
        			backup(jarPath);
        			endList.put(cfgName, jarPath);
        		}else{
        			endList.put(cfgName, ">>>>>>>>>>>NO UPDATE<<<<<<<<<<<");
        		}
        		startList.remove(0);
        	}

        	btnAddConfigFile.setEnabled(true);
        	btnAddAllConfig.setEnabled(true);
        	isStart = false;

        } catch (Exception e) {
        	e.printStackTrace();
        }
	}

	private void backup(String jarPath){
		FileOprate fileop = new FileOprate();

		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		long logfileName = Long.valueOf(sdf.format(new Date()));
		
		String logPath = ContextUtil.getHome() + ContextUtil.getLogPath();

		fileop.newFolder(logPath);
		fileop.newFolder(logPath + logfileName);

		File jar = new File(jarPath);
		String target = logPath + logfileName + "/" + jar.getName();
		String newName = target;
		int i = 1;
		while(new File(newName).exists()){
			newName = target + "_" + i;
			i++;
		}
		fileop.copyFile(jarPath, newName);
	}

}
